<!--
 * @Author: CC-TSR
 * @Date: 2021-01-21 11:14:34
 * @LastEditTime: 2021-01-22 10:32:44
 * @LastEditors: xiejiancheng1999@qq.com
 * @Description: 
 * @FilePath: \前端\src\components\MapTree\LineCheckSider.vue
 * @可以输入预定的版权声明、个性签名、空行等
-->
<template>
  <div class="model" v-if="checkTab">
    <div class="project-info">
      <Button
        size="small"
        style="padding: 0"
        type="text"
        @click="backToLayerSider"
        ><Icon type="md-arrow-round-back" />返回
      </Button>
      <Divider orientation="left"><h3>项目信息</h3></Divider>
      <Row :gutter="16">
        <Col span="8"><span>项目名称</span></Col>
        <Col span="16"
          ><Select v-model="projectType" style="width: 100%"
        /></Col>
      </Row>
      <Row :gutter="16">
        <Col span="8"><span>项目类型</span></Col>
        <Col span="16"
          ><Select v-model="projectType" style="width: 100%"
        /></Col>
      </Row>
      <Row :gutter="16">
        <Col span="8"><span>建设单位</span></Col>
        <Col span="16"
          ><Select v-model="projectType" style="width: 100%"
        /></Col>
      </Row>
    </div>
    <div class="control-line">
      <Divider orientation="left"><h3>控制线</h3></Divider>
      <Row :gutter="16">
        <Col span="16"><span>生态安全控制线</span></Col>
        <Col span="8">
          <i-switch v-model="switch0" />
        </Col>
      </Row>
      <Row :gutter="16">
        <Col span="16"><span>重大基础设施控制线</span></Col>
        <Col span="8">
          <i-switch v-model="switch1" />
        </Col>
      </Row>
      <Row :gutter="16">
        <Col span="16"><span>永久基本农田控制线</span></Col>
        <Col span="8">
          <i-switch v-model="switch2" />
        </Col>
      </Row>
      <Row :gutter="16">
        <Col span="16"><span>文物古迹保护控制线</span></Col>
        <Col span="8">
          <i-switch v-model="switch3" />
        </Col>
      </Row>
    </div>
    <div class="control-line">
      <Divider orientation="left"><h3>监测范围</h3></Divider>
      <Row :gutter="16">
        <Col span="8"><h4>获取方式:</h4></Col>
        <Col span="16">
          <ButtonGroup size="small" shape="circle">
            <Button type="info" ghost>导入</Button>
            <Button type="info" @click="drawPolygon" ghost>手绘</Button>
            <Button type="info" @click="inputPolygon" ghost>录入</Button>
          </ButtonGroup>
        </Col>
      </Row>
      <Row :gutter="16">
        <Col span="12">
          <Button @click="check" :loading="checkState" type="primary">
            <span v-if="!checkState">开始检测</span>
            <span v-else>检测中...</span>
          </Button>
        </Col>
        <Col span="12">
          <Button type="primary" @click="cleanRes">清除结果</Button>
        </Col>
      </Row>
    </div>
  </div>
  <LineCheckResult
    :resdata="Object.assign({}, resultData)"
    @back="back"
    @flashGraphic="flashGraphic"
    v-else
  />
</template>

<script>
import axios2 from "@/plugins/axios";
import config from "@/config.js";
import { mapState, mapActions } from "vuex";
import LineCheckResult from "./LineCheckResult";
import Graphic from "@arcgis/core/Graphic";
import Draw from "@arcgis/core/views/draw/Draw";
import GraphicsLayer from "@arcgis/core/layers/GraphicsLayer";

let flashHook, stopFlashHook, highlight;
export default {
  name: "LineCheckSider",
  components: { LineCheckResult },
  data() {
    return {
      projectType: "",
      switch0: true,
      switch1: true,
      switch2: true,
      switch3: true,
      checkState: false,
      checkTab: true,
      resultData: null,
      targetPolygonGraphic: null,
      resultGraphicLayers: [],
    };
  },
  computed: {
    ...mapState({
      view: (state) => state.oneMap.view,
      map: (state) => state.oneMap.map,
    }),
    checkLines() {
      let res = [];
      if (this.switch0) {
        res.push(0);
      }
      if (this.switch1) {
        res.push(1);
      }
      if (this.switch2) {
        res.push(2);
      }
      if (this.switch3) {
        res.push(3);
      }
      return res;
    },
    polygons() {
      return [
        {
          geometryType: "esriGeometryPolygon",
          geometries: [
            this.targetPolygonGraphic.toJSON().geometry,
            // {
            //   rings: [
            //     [
            //       [109.24410618600007, 34.875222517000054],
            //       [109.25790706000004, 34.875508052000043],
            //       [109.26295151700003, 34.86703717100005],
            //       [109.25213443000007, 34.864091532000032],
            //       [109.24286517200005, 34.870041108000066],
            //       [109.24410618600007, 34.875222517000054],
            //     ],
            //   ],
            //   spatialReference: { wkid: 4326 },
            // },
          ],
        },
      ];
    },
  },
  methods: {
    ...mapActions("oneMap", ["updateSiderPanel"]),

    createPolygonGraphic(vertices) {
      let self = this;
      self.view.graphics.removeAll();
      var polygon = {
        type: "polygon", // autocasts as Polygon
        rings: vertices,
        spatialReference: self.view.spatialReference,
      };
      let targetCheckedPolygonSybol = {
        type: "simple-fill", // autocasts as new SimpleFillSymbol()
        color: [255, 255, 255, 0],
        outline: {
          // autocasts as new SimpleLineSymbol()
          color: [206, 60, 246],
          width: 2,
          style: "short-dash",
        },
      };
      var graphic = new Graphic({
        geometry: polygon,
        symbol: targetCheckedPolygonSybol,
      });
      self.targetPolygonGraphic = graphic;
      self.view.graphics.add(graphic);
    },
    drawPolygon() {
      let self = this;

      let draw = new Draw({ view: self.view });

      let action = draw.create("polygon");
      action.on("vertex-add", function (evt) {
        self.createPolygonGraphic(evt.vertices);
      });
      // PolygonDrawAction.vertex-remove
      // Fires when the "Z" key is pressed to undo the last added vertex
      action.on("vertex-remove", function (evt) {
        self.createPolygonGraphic(evt.vertices);
      });

      // Fires when the pointer moves over the view
      action.on("cursor-update", function (evt) {
        self.createPolygonGraphic(evt.vertices);
      });

      // Add a graphic representing the completed polygon
      // when user double-clicks on the view or presses the "C" key
      action.on("draw-complete", function (evt) {
        self.createPolygonGraphic(evt.vertices);
        console.log(evt);
      });
    },
    inputPolygon() {},
    flashGraphic(graInfo) {
      if (flashHook) clearInterval(flashHook);
      if (stopFlashHook) clearTimeout(stopFlashHook);
      if (highlight) this.view.graphics.remove(highlight);
      let targetHighightLayer = this.resultGraphicLayers.find(
        (layer) => layer.title === graInfo[0].toString()
      );
      // Create a symbol for highlight the graphic
      let highlightSybol = {
        type: "simple-fill", // autocasts as new SimpleFillSymbol()
        color: [13, 242, 200],
        outline: {
          // autocasts as new SimpleLineSymbol()
          color: [255, 255, 255],
          width: 1,
        },
      };

      if (targetHighightLayer) {
        let targetHightlightGraphic =
          targetHighightLayer.graphics.items[graInfo[1]];

        this.view
          .goTo(targetHightlightGraphic, {
            duration: 200,
          })
          .catch(function (error) {
            console.error(error);
          });
        highlight = targetHightlightGraphic.clone();
        highlight.symbol = highlightSybol;
        let highlightControl = false;
        flashHook = setInterval(() => {
          highlightControl = !highlightControl;
          if (highlightControl) this.view.graphics.add(highlight);
          else this.view.graphics.remove(highlight);
        }, 200);
        stopFlashHook = setTimeout(() => {
          if (flashHook) clearInterval(flashHook);
          this.view.graphics.remove(highlight);
        }, 3000);
      }
    },
    check() {
      this.cleanRes();
      if (!this.checkLines.length) {
        this.$Message.warning({
          background: true,
          content: "未选择需要检测得控制线，检测完成",
          duration: 3,
        });
        return;
      }
      if (!this.targetPolygonGraphic) {
        this.$Message.warning({
          background: true,
          content: "请先绘制或导入检测面",
          duration: 3,
        });
        return;
      }
      this.checkState = true;
      let relations = [];
      for (let index = 0; index < this.checkLines.length; index++) {
        relations.push("intersect");
      }
      //#region
      let jd = {
        projectInfos: {
          projectInfos: [
            { name: "test", type: "房地产建设项目", department: "2112" },
          ],
        },
        checkFeatures: {
          polygons: this.polygons,
        },
        layers: this.checkLines.join(","),
        relations: relations.join(","),
        servicesfields: "DLMC,MJ;MJ,ZDJCSSLDMC;MJ;",
        sr: 4326,
        f: "json",
      };
      const fd = new URLSearchParams();
      Object.keys(jd).forEach((key) => {
        if (key === "projectInfos" || key === "checkFeatures") {
          fd.append(key, JSON.stringify(jd[key]));
        } else {
          fd.append(key, jd[key]);
        }
      });
      // var headers = new Headers();
      // headers.push("Content-Type", "application/x-www-form-urlencoded");
      //#endregion
      axios2
        .post(
          "http://124.114.148.199:6081/arcgis/rest/services/kzx/MapServer/exts/MultiRuleInOneSOE/MultiRuleinOneSOE",
          fd
          // headers
        )
        .then((res) => {
          // 获取到了交集面开始绘制
          console.log(res.data);
          let that = this;
          let colors = [
            [162, 68, 137, 0.8],
            [240, 61, 192, 0.8],
            [254, 1, 94, 0.8],
            [231, 13, 17, 0.8],
          ];

          let data = res.data;
          let lineType = 0;
          data.Results.forEach((result) => {
            let tempGraphicLayer = new GraphicsLayer();
            if (result.geometries.length) {
              result.geometries.forEach((resGeo) => {
                let polygon = {
                  type: "polygon", // autocasts as new Polygon()
                  rings: resGeo.rings,
                };

                // Create a symbol for rendering the graphic
                let fillSymbol = {
                  type: "simple-fill", // autocasts as new SimpleFillSymbol()
                  color: colors[lineType],
                  outline: {
                    // autocasts as new SimpleLineSymbol()
                    color: [255, 255, 255],
                    width: 1,
                  },
                };

                // Add the geometry and symbol to a new graphic
                let polygonGraphic = new Graphic({
                  geometry: polygon,
                  symbol: fillSymbol,
                  popupTemplate: {
                    title: "{NAME}",
                    content: [
                      {
                        // Pass in the fields to display
                        type: "fields",
                        fieldInfos: [
                          {
                            fieldName: "NAME",
                            label: "Name",
                          },
                          {
                            fieldName: "REGION",
                            label: "Region",
                          },
                        ],
                      },
                    ],
                  },
                });
                tempGraphicLayer.add(polygonGraphic);
                // resPolygonGraphics.push(polygonGraphic);
              });
            }
            tempGraphicLayer.title = result.layer;
            that.resultGraphicLayers.push(tempGraphicLayer);

            lineType += 1;
          });
          that.map.addMany(that.resultGraphicLayers);

          // that.view.graphics.addMany(resPolygonGraphics);
          that.view.goTo(that.targetPolygonGraphic);

          that.checkState = false;
          that.resultData = data;
          that.checkTab = false;
        });
    },
    cleanRes() {
      if (this.resultGraphicLayers.length) {
        this.resultGraphicLayers.forEach((layer) => {
          this.map.remove(layer);
        });
      }
      this.resultGraphicLayers = [];
    },
    back() {
      this.checkTab = true;
    },
    backToLayerSider() {
      this.updateSiderPanel("layerTree");
    },
  },
  created() {
    this.$emit("showMap", true);
  },
};
</script>

<style scoped>
.model {
  padding: 1rem 1rem;
  overflow-y: auto;
}
.ivu-row {
  height: 2rem !important;
  margin-bottom: 1rem;
}
</style>
